//
// Created by 吴喆 on 2020/3/5.
//

#include "SpriteRender.h"
#include "../util/ConfigUtil.h"


SpriteRenderer::SpriteRenderer(Shader *shader) : Renderer(shader) {
    initRenderData();
}

void SpriteRenderer::initRenderData() {
    // Configure VAO/VBO
    GLuint VBO;
    GLfloat vertices[] = {
            // Pos      // Tex
            0.0f, 1.0f, 0.0f, 1.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            1.0f, 0.0f, 1.0f, 0.0f,

            0.0f, 1.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 1.0f, 0.0f,
            1.0f, 1.0f, 1.0f, 1.0f
    };

    glGenVertexArrays(1, &this->quadVAO);
    glGenBuffers(1, &VBO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glBindVertexArray(this->quadVAO);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid *) 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}


void SpriteRenderer::DrawSprite(Camera *camera, Texture2D *texture, glm::vec2 position, glm::vec2 size, float rotate, bool hFlip, bool vFlip, bool useColor, glm::vec4 color) {
    otho = false;
    if (otho) {
        size *= std::stoi(ConfigUtil::getProp(ConfigConst::SCREEN_HEIGHT)) / 10;
        position *= std::stoi(ConfigUtil::getProp(ConfigConst::SCREEN_HEIGHT)) / 10;
    }
    Renderer::shader->use();
    this->shader->setInteger("needFlipH", hFlip);
    this->shader->setInteger("needFlipV", vFlip);
    this->shader->setInteger("image", 0);
    this->shader->setMatrix4("projection", otho?camera->getOthoProjectionMatrix():camera->getPerspectiveViewMatrix());
    this->shader->setMatrix4("view", otho?glm::mat4():camera->getViewMatrix());
    if (useColor) {
        this->shader->setInteger("exist", 1);
        this->shader->setVector4f("color", color);
    } else {
        this->shader->setInteger("exist", 0);
    }

    glm::mat4 model;
    // First translate (transformations are: scale happens first, then rotation and then finall translation happens; reversed order)
    model = glm::translate(model, glm::vec3(position, 0.0f));
    // 将物体移到原来位置
    model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f));
    // Then rotate
    model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f));
    // Move origin back
    model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f));
    model = glm::scale(model, glm::vec3(size, 1.0f)); // Last scale

    this->shader->setMatrix4("model", model);
    // Render textured quad
//    this->shader->setVector3f("spriteColor", color);

    glActiveTexture(GL_TEXTURE0);
    texture->bind();
    glBindVertexArray(this->quadVAO);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);

    shader->disuse();
}

